﻿using Naruto.Subscribe.Interface;
using Naruto.TaskManagement.Entitys.Const;
using Naruto.TaskManagement.Entitys.DTO;
using Naruto.TaskManagement.Entitys.Enums;
using Naruto.TaskManagement.Entitys.Models;
using Naruto.TaskManagement.Infrastructure;
using Naruto.TaskManagement.Infrastructure.Interface;
using Naruto.TaskManagement.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.TaskManagement.Application
{
    public class TaskRecordApps : IApp
    {
        private readonly ITaskRecordRepository taskRecordRepository;

        private readonly ITaskRecordImageRepository taskRecordImageRepository;

        private readonly ITaskManageUnitOfWork unitOfWork;


        private readonly INarutoPublish narutoPublish;

        private readonly IUserRepository userRepository;


        public TaskRecordApps(ITaskRecordRepository _taskRecordRepository, ITaskRecordImageRepository _taskRecordImageRepository, ITaskManageUnitOfWork _unitOfWork, INarutoPublish _narutoPublish, IUserRepository _userRepository)
        {
            taskRecordRepository = _taskRecordRepository;
            taskRecordImageRepository = _taskRecordImageRepository;
            unitOfWork = _unitOfWork;
            narutoPublish = _narutoPublish;
            userRepository = _userRepository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public async Task<NarutoResult> Add(TaskRecordAddDTO info)
        {
            if (info == null)
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.title.IsNullEmpty())
            {
                return new NarutoFailResult("请输入标题");
            }
            if (info.description.IsNullEmpty())
            {
                return new NarutoFailResult("请输入描述");
            }
            if (info.endDate.IsNullEmpty())
            {
                return new NarutoFailResult("请输入截至日期");
            }
            var taskRecord = new Entitys.Models.TaskRecord
            {
                CreateTime = DateTime.Now,
                CreateUser = info.createUser,
                Description = info.description,
                EndDate = Convert.ToDateTime(info.endDate),
                Level = info.level,
                Status = (int)TaskRecordStatusEnum.Pending,
                Title = info.title,
                Id = SnowFlakeHelper.NewID(),
                AppointUser = info.appointUser ?? ""
            };
            await taskRecordRepository.Add(taskRecord);

            //添加图片
            if (info.fileList != null && info.fileList.Count() > 0)
            {
                await taskRecordImageRepository.Add(info.fileList.Select(a => new Entitys.Models.TaskRecordImage
                {
                    ImageUrl = a,
                    Id = SnowFlakeHelper.NewID(),
                    TaskRecordId = taskRecord.Id
                }).ToList());
            }

            var res = await unitOfWork.SaveChangeAsync();
            if (res > 0)
            {
                if (!info.appointUser.IsNullEmpty())
                {
                    //发送邮件通知
                    await narutoPublish.PublishAsync(ConstObject.SendTaskEmailSubscribeKey, new TaskSendEmailDTO
                    {
                        Id = taskRecord.Id,
                        AppointUser = taskRecord.AppointUser,
                        Title = "新任务生成"
                    });
                }
                return new NarutoSuccessResult("操作成功");
            }
            return new NarutoFailResult("操作失败");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public async Task<NarutoResult> Update(TaskRecordAddDTO info)
        {
            if (info.id.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.title.IsNullEmpty())
            {
                return new NarutoFailResult("请输入标题");
            }
            if (info.description.IsNullEmpty())
            {
                return new NarutoFailResult("请输入描述");
            }
            if (info.endDate.IsNullEmpty())
            {
                return new NarutoFailResult("请输入截至日期");
            }
            await taskRecordRepository.Update(info.id, title: info.title, description: info.description, level: info.level, endDate: Convert.ToDateTime(info.endDate), appointUser: info.appointUser);

            //删除图片
            await taskRecordImageRepository.Delete(info.id);
            //添加图片
            if (info.fileList != null && info.fileList.Count() > 0)
            {
                await taskRecordImageRepository.Add(info.fileList.Select(a => new Entitys.Models.TaskRecordImage
                {
                    ImageUrl = a,
                    Id = SnowFlakeHelper.NewID(),
                    TaskRecordId = info.id
                }).ToList());
            }

            var res = await unitOfWork.SaveChangeAsync();
            if (res > 0)
            {
                if (!info.appointUser.IsNullEmpty())
                {
                    //发送邮件通知
                    await narutoPublish.PublishAsync(ConstObject.SendTaskEmailSubscribeKey, new TaskSendEmailDTO
                    {
                        Id = info.id,
                        AppointUser = info.appointUser,
                        Title = "任务信息变更"
                    });
                }
                return new NarutoSuccessResult("操作成功");
            }
            return new NarutoFailResult("操作失败");
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="info"></param>
        /// <param name="status">任务状态</param>
        /// <returns></returns>
        public async Task<NarutoResult> GetList(int status, TaskRecordGetListDTO info)
        {
            if (info == null)
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.organizationId.IsNullEmpty())
            {
                return new NarutoFailResult("组织信息错误");
            }
            if (info.pageIndex <= 0)
            {
                info.pageIndex = 1;
            }
            if (info.pageSize <= 0)
            {
                info.pageSize = 10;
            }

            //获取数据
            var res = await taskRecordRepository.GetListByPage(status, info.organizationId, info.keyword, info.type, info.userName, info.pageIndex, info.pageSize);

            return new NarutoSuccessResult(_msg: "操作成功"
                , _data: res.list, _recordCount: res.count);
        }
        /// <summary>
        /// 获取数据总数
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="type"></param>
        /// <param name="userName">用户名</param>
        /// <param name="organizationId">组织id</param>
        /// <returns></returns>
        public async Task<NarutoResult> GetListCount(TaskRecordGetListDTO info)
        {
            if (info == null)
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.organizationId.IsNullEmpty())
            {
                return new NarutoFailResult("组织信息错误");
            }

            //获取数据
            var res = await taskRecordRepository.GetListCount(info.organizationId, info.keyword, info.type, info.userName);

            return new NarutoSuccessResult(_msg: "操作成功"
                , _data: res);
        }
        /// <summary>
        /// 根据id 获取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<NarutoResult> GetById(string id)
        {
            if (id.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误");
            }
            //获取记录信息
            var taskRecordInfo = await taskRecordRepository.GetById(id);

            if (taskRecordInfo == null)
            {
                return new NarutoFailResult("无效的参数");
            }

            taskRecordInfo.ImgesList = await taskRecordImageRepository.GetImages(id);
            //获取用户的名称
            if (!taskRecordInfo.AppointUser.IsNullEmpty())
            {
                taskRecordInfo.AppointName = await userRepository.GetName(taskRecordInfo.AppointUser);
            }
            return new NarutoSuccessResult("操作成功", taskRecordInfo);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<NarutoResult> UpdateStatus(string id, UpdateStatusDTO info)
        {
            if (id.IsNullEmpty() || info == null)
            {
                return new NarutoFailResult("参数错误");
            }
            if (info.status < 0)
            {
                return new NarutoFailResult("参数错误.");
            }
            if (info.operationUser.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误..");
            }

            await taskRecordRepository.UpdateStatus(id, info.status, info.operationUser, info.remark);

            await unitOfWork.SaveChangeAsync();

            //发送邮件通知
            await narutoPublish.PublishAsync(ConstObject.SendTaskEmailSubscribeKey, new TaskSendEmailDTO
            {
                Id = id,
                Title = "任务变更通知"
            });

            return new NarutoSuccessResult("操作成功");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<NarutoResult> Delete(string id, TaskRecordDeleteDTO info)
        {
            if (id.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误");
            }
            if (info == null || info.operationUser.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误.");
            }
            await taskRecordRepository.Delete(id, info.operationUser);

            await unitOfWork.SaveChangeAsync();

            return new NarutoSuccessResult("操作成功");
        }
        /// <summary>
        /// 获取我的任务
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<NarutoResult> GetMyTaskCount(string userName)
        {
            if (userName.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误");
            }
            var res = await taskRecordRepository.GetMyTaskCount(userName);

            return new NarutoSuccessResult("操作成功", new
            {
                res.myCreateCount,
                res.appointMyTask
            });
        }
    }
}
